/**
 * Agent账号管理Store（Pinia版本）
 */
import { defineStore } from 'pinia'

export const useAgentStore = defineStore('agent', {
  state: () => ({
    // 客户端列表
    clients: [],
    // 当前选中的客户端
    selectedClient: null,
    // WebSocket连接状态
    wsConnected: false,
    // 搜索结果列表
    searchResults: [],
    // 订单列表
    orders: []
  }),

  getters: {
    /**
     * 在线客户端
     */
    onlineClients: (state) => {
      return state.clients.filter(c => c.online_status === 'online')
    },

    /**
     * 离线客户端
     */
    offlineClients: (state) => {
      return state.clients.filter(c => c.online_status === 'offline')
    },

    /**
     * 搜索类型的客户端
     */
    searchClients: (state) => {
      return state.clients.filter(c => c.client_type === 'search' && c.online_status === 'online')
    },

    /**
     * 下单类型的客户端
     */
    orderClients: (state) => {
      return state.clients.filter(c => c.client_type === 'order' && c.online_status === 'online')
    },

    /**
     * 已登录的客户端
     */
    loggedInClients: (state) => {
      return state.clients.filter(c => c.login_status === 'logged_in')
    }
  },

  actions: {
    /**
     * 设置客户端列表
     */
    setClients(clients) {
      this.clients = clients
    },

    /**
     * 添加或更新单个客户端
     */
    updateClient(client) {
      const index = this.clients.findIndex(c => c.client_id === client.client_id)
      if (index > -1) {
        // 更新现有客户端
        Object.assign(this.clients[index], client)
      } else {
        // 添加新客户端
        this.clients.push(client)
      }
    },

    /**
     * 移除客户端
     */
    removeClient(clientId) {
      const index = this.clients.findIndex(c => c.client_id === clientId)
      if (index > -1) {
        this.clients.splice(index, 1)
      }
      // 如果移除的是当前选中的客户端，清除选中状态
      if (this.selectedClient && this.selectedClient.client_id === clientId) {
        this.selectedClient = null
      }
    },

    /**
     * 选择客户端
     */
    selectClient(clientId) {
      const client = this.clients.find(c => c.client_id === clientId)
      if (client) {
        this.selectedClient = client
      }
    },

    /**
     * 设置WebSocket连接状态
     */
    setWSConnected(connected) {
      this.wsConnected = connected
    },

    /**
     * 添加搜索结果
     */
    addSearchResult(result) {
      this.searchResults.unshift(result)
    },

    /**
     * 设置搜索结果列表
     */
    setSearchResults(results) {
      this.searchResults = results
    },

    /**
     * 清空搜索结果
     */
    clearSearchResults() {
      this.searchResults = []
    },

    /**
     * 添加订单
     */
    addOrder(order) {
      this.orders.unshift(order)
    },

    /**
     * 设置订单列表
     */
    setOrders(orders) {
      this.orders = orders
    },

    /**
     * 更新客户端默认地址
     */
    updateClientAddress({ clientId, addressId }) {
      const client = this.clients.find(c => c.client_id === clientId)
      if (client) {
        client.default_address_id = addressId
      }
    }
  }
})

